<?php

namespace app\model\oa;

use think\Model;

class WorkflowLog extends Model
{
    // 表名
    protected $name = 'oa_workflow_log';

    // 自动时间戳
    protected $autoWriteTimestamp = 'create_time';

    // 关联流程记录
    public function record()
    {
        return $this->belongsTo('app\model\oa\WorkflowRecord', 'record_id', 'id');
    }

    // 关联操作用户
    public function user()
    {
        return $this->belongsTo('app\model\admin\User', 'user_id', 'id');
    }

    // 获取流程日志列表
    public static function getLogs($recordId, $params = [])
    {
        $query = self::with(['user'])
            ->where('record_id', $recordId)
            ->order('create_time', 'desc');

        return $query->paginate([
            'list_rows' => $params['limit'] ?? 20,
            'page' => $params['page'] ?? 1
        ]);
    }

    // 创建流程日志
    public static function createLog($recordId, $action, $userId, $remark = '')
    {
        return self::create([
            'record_id' => $recordId,
            'action' => $action,
            'user_id' => $userId,
            'remark' => $remark,
            'create_time' => time()
        ]);
    }

    // 批量创建日志
    public static function batchCreateLogs($logs)
    {
        $insertData = [];
        $time = time();
        
        foreach ($logs as $log) {
            $insertData[] = [
                'record_id' => $log['record_id'],
                'action' => $log['action'],
                'user_id' => $log['user_id'],
                'remark' => $log['remark'] ?? '',
                'create_time' => $time
            ];
        }

        return self::insertAll($insertData);
    }

    // 获取用户操作日志
    public static function getUserLogs($userId, $params = [])
    {
        $query = self::with(['record', 'record.template'])
            ->where('user_id', $userId)
            ->order('create_time', 'desc');

        // 流程筛选
        if (!empty($params['record_id'])) {
            $query->where('record_id', $params['record_id']);
        }

        // 操作类型筛选
        if (!empty($params['action'])) {
            $query->where('action', $params['action']);
        }

        // 时间范围筛选
        if (!empty($params['create_time'])) {
            $query->whereBetween('create_time', $params['create_time']);
        }

        return $query->paginate([
            'list_rows' => $params['limit'] ?? 15,
            'page' => $params['page'] ?? 1
        ]);
    }

    // 获取流程操作统计
    public static function getActionStats($recordId)
    {
        $stats = self::where('record_id', $recordId)
            ->group('action')
            ->field('action, COUNT(*) as count')
            ->select()
            ->toArray();

        $result = [];
        foreach ($stats as $stat) {
            $result[$stat['action']] = $stat['count'];
        }

        return $result;
    }

    // 获取用户操作统计
    public static function getUserActionStats($userId, $days = 30)
    {
        $startTime = strtotime('-' . $days . ' days');
        
        $stats = self::where('user_id', $userId)
            ->where('create_time', '>=', $startTime)
            ->group('action')
            ->field('action, COUNT(*) as count')
            ->select()
            ->toArray();

        $result = [];
        foreach ($stats as $stat) {
            $result[$stat['action']] = $stat['count'];
        }

        return $result;
    }

    // 获取操作类型名称
    public function getActionNameAttr($value)
    {
        $actionMap = [
            'create' => '创建流程',
            'submit' => '提交流程',
            'approve' => '同意',
            'reject' => '拒绝',
            'cancel' => '取消',
            'complete' => '完成',
            'assign' => '转交',
            'back' => '退回',
            'timeout' => '超时',
            'remind' => '催办'
        ];

        return $actionMap[$value] ?? $value;
    }

    // 获取操作时间格式化
    public function getCreateTimeFormatAttr($value, $data)
    {
        return date('Y-m-d H:i:s', $data['create_time']);
    }

    // 获取相对时间
    public function getRelativeTimeAttr($value, $data)
    {
        $diff = time() - $data['create_time'];
        
        if ($diff < 60) {
            return '刚刚';
        } elseif ($diff < 3600) {
            return floor($diff / 60) . '分钟前';
        } elseif ($diff < 86400) {
            return floor($diff / 3600) . '小时前';
        } elseif ($diff < 2592000) {
            return floor($diff / 86400) . '天前';
        } else {
            return date('Y-m-d', $data['create_time']);
        }
    }

    // 搜索器：流程ID
    public function searchRecordIdAttr($query, $value)
    {
        return $query->where('record_id', $value);
    }

    // 搜索器：操作用户
    public function searchUserIdAttr($query, $value)
    {
        return $query->where('user_id', $value);
    }

    // 搜索器：操作类型
    public function searchActionAttr($query, $value)
    {
        return $query->where('action', $value);
    }

    // 搜索器：创建时间范围
    public function searchCreateTimeAttr($query, $value)
    {
        return $query->whereBetween('create_time', $value);
    }

    // 搜索器：关键字搜索
    public function searchKeywordAttr($query, $value)
    {
        return $query->whereLike('remark', '%' . $value . '%');
    }
}